# -*- coding: utf-8 -*- 

import StringIO

import urllib
import json
import pycurl
import webbrowser
import pysvn

import env



#SVN Class
class svn():
    #SVN登录
    @staticmethod
    def login(realm, username, may_save):
        return True, env.svn_username, env.svn_password, False

    #SVN SSL回调函数
    @staticmethod
    def ssl_server_trust_prompt(trust_data):
        return True, trust_data['failures'], True

    #获取SVN最新版本号
    @staticmethod
    def show_last_version(url):
        client = pysvn.Client()
        revision_start = pysvn.Revision(pysvn.opt_revision_kind.head)
        
        client.callback_get_login = svn.login
        client.callback_ssl_server_trust_prompt = svn.ssl_server_trust_prompt
        log_list = client.log(url, revision_start , limit=1)
        result = log_list[0].get("revision").number
        return result

#发送邮件
def send_mail(to, cc, subject, body):
    mailto = "mailto:%s?cc=%s&subject=%s&body=%s" % (to, cc, subject, body)
    webbrowser.open_new_tab(mailto)


#获取一条提案信息
def show_issue(issue_id):
    jira_base_url = "http://issue.internal.sina.com.cn/"

    query_str = urllib.urlencode({"os_username":env.svn_username, "os_password":env.svn_password})
    issue_url = jira_base_url + "rest/api/2.0.alpha1/issue/"+issue_id+"?"+query_str
    
    body = StringIO.StringIO() 
    ch = pycurl.Curl()
    ch.setopt(ch.URL, issue_url)
    ch.setopt(ch.WRITEFUNCTION, body.write)
    ch.perform() 
    
    response = body.getvalue()
    response = json.loads(response)
    body.close()

    summary = response["fields"]["summary"]["value"]
    result = {"summary":summary, "url":jira_base_url+"browse/"+issue_id}
    return result
